package top.lethelh.jianoa.config.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.lethelh.jianoa.db.pojo.TbUser;
import top.lethelh.jianoa.service.UserService;

import java.util.Set;

@Component
public class OAth2Realm extends AuthorizingRealm {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 权限授予（在用户登录成功时授予权限）
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
        TbUser user = (TbUser) collection.getPrimaryPrincipal();
        int userId = user.getId();
        // 根据用户id获取用户权限
        Set<String> permissionSet = userService.searchUserPermissions(userId);
        // 创建一个 SimpleAuthorizationInfo 对象（简单授权对象）
        SimpleAuthorizationInfo saInfo = new SimpleAuthorizationInfo();
        // 将上文的权限集合赋予saInfo
        saInfo.setStringPermissions(permissionSet);
        return saInfo;
    }

    /**
     * 身份识别（当用户登录的时候首先进行校验）
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
        // 从令牌字符串中获取校验信息
        String accessToken = (String) at.getPrincipal();
        // 通过 jwtUtil 工具类获得userId
        int userId = jwtUtil.getUserId(accessToken);
        // 查询 mysql 中用户表是否有该用户
        TbUser user = userService.searchById(userId);
        // 若不存在，则抛出异常
        if (user == null) {
            // 抛出Shiro框架里的账户被锁定异常
            throw new LockedAccountException("您的账号已被禁用,请联系管理员");
        }
        // 创建一个 SimpleAuthenticationInfo 对象（简单认证对象）
        SimpleAuthenticationInfo saInfo = new SimpleAuthenticationInfo(user, accessToken, getName());
        // 返回回去
        return saInfo;
    }
}
